package com.example.demo.service.impl;

import com.example.demo.context.BaseContext;
import com.example.demo.mapper.DietMapper;
import com.example.demo.pojo.entity.Diet;
import com.example.demo.pojo.entity.UserDiet;
import com.example.demo.service.DietService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
public class DietServiceImpl implements DietService {

    @Autowired
    private DietMapper dietMapper;

    @Override
    public List<UserDiet> getDiet() {
        Long userId= BaseContext.getCurrentId();
        List<UserDiet> userDietList= dietMapper.getDietByUserId(userId);
        if(userDietList==null|| userDietList.isEmpty()){
            List<Diet> xiwei=dietMapper.getDietBytype("纤维素");
            List<Diet> zhifan=dietMapper.getDietBytype("健康脂肪");
            List<Diet> tanshui=dietMapper.getDietBytype("碳水");
            List<Diet> daomai=dietMapper.getDietBytype("蛋白质");

            Random random=new Random();
            int i=0;
            while(i<3){
                UserDiet userDiet=new UserDiet();
                String food="";
                if(i==0){
                    int x=random.nextInt(xiwei.size());
                    food+=xiwei.get(x).getName();
                    x=random.nextInt(tanshui.size());
                    food+=","+tanshui.get(x).getName();
                    x=random.nextInt(daomai.size());
                    food+=","+daomai.get(x).getName();
                    userDiet.setTime("早");
                    userDiet.setFood(food);
                }else {
                    int x=random.nextInt(xiwei.size());
                    food+=xiwei.get(x).getName();
                    x=random.nextInt(tanshui.size());
                    food+=","+tanshui.get(x).getName();
                    x=random.nextInt(daomai.size());
                    food+=","+daomai.get(x).getName();
                    userDiet.setFood(food);
                    x= random.nextInt(zhifan.size());
                    food+=","+zhifan.get(x).getName();
                    userDiet.setFood(food);
                    if(i==1){
                        userDiet.setTime("中");
                    }else{
                        userDiet.setTime("晚");
                    }
                }
                userDiet.setUserId(BaseContext.getCurrentId());
                userDiet.setCreateTime(LocalDateTime.now());
                userDietList.add(userDiet);
                dietMapper.insert(userDiet);
                i++;
            }
        }
        return userDietList;
    }

    @Override
    public void finish(Long id) {
        UserDiet userDiet = new UserDiet();
        userDiet.setId(id);
        userDiet.setUserId(BaseContext.getCurrentId());
        userDiet.setIsFinish(1);
        dietMapper.update(userDiet);
    }
}
